import React, { useState } from 'react'
import {
    View,
    TouchableOpacity,
    Alert,
    TextInput,
    Modal,
} from 'react-native'
import { Text, Icon } from '@rneui/themed'
import { leaveDetailStyles } from '../../../styles/leaveDetailStyles'
import { TaskApi } from '../../../api/process'

interface ApprovalButtonsProps {
    taskId: string
    onApprovalComplete?: () => void // 审批完成后的回调
    style?: any // 自定义样式
    showFullWidth?: boolean // 是否显示全宽按钮
}

const ApprovalButtons: React.FC<ApprovalButtonsProps> = ({
    taskId,
    onApprovalComplete,
    style,
    showFullWidth = false
}) => {
    // 审批意见输入相关状态
    const [showApprovalModal, setShowApprovalModal] = useState(false)
    const [approvalType, setApprovalType] = useState<'approve' | 'reject'>('approve')
    const [approvalReason, setApprovalReason] = useState('')

    // 处理同意请假
    const handleApprove = () => {
        setApprovalType('approve')
        setApprovalReason('')
        setShowApprovalModal(true)
    }

    // 处理不同意请假
    const handleReject = () => {
        setApprovalType('reject')
        setApprovalReason('')
        setShowApprovalModal(true)
    }
    
    // 提交审批
    const handleSubmitApproval = async () => {
        try {
            if (!taskId) {
                Alert.alert('错误', '缺少任务ID，无法进行审批')
                return
            }
            
            if (approvalType === 'reject' && !approvalReason.trim()) {
                Alert.alert('提示', '请输入拒绝原因')
                return
            }
            
            const data = {
                id: taskId,
                reason: approvalReason.trim() || (approvalType === 'approve' ? '同意' : '拒绝')
            }
            
            if (approvalType === 'approve') {
                await TaskApi.approveTask(data)
                Alert.alert('成功', '已同意请假申请')
            } else {
                await TaskApi.rejectTask(data)
                Alert.alert('成功', '已拒绝请假申请')
            }
            
            // 关闭弹窗并调用回调
            setShowApprovalModal(false)
            onApprovalComplete?.()
        } catch (error) {
            console.error('审批失败:', error)
            Alert.alert('错误', '审批失败，请稍后重试')
        }
    }
    
    // 关闭审批弹窗
    const handleCloseApprovalModal = () => {
        setShowApprovalModal(false)
        setApprovalReason('')
    }

    const buttonContainerStyle = showFullWidth 
        ? [{ flexDirection: 'row', gap: 8, paddingTop: 8 }, style] 
        : [{ flexDirection: 'row', gap: 8 }, style]

    const approveButtonStyle = showFullWidth 
        ? [leaveDetailStyles.cancelButton, leaveDetailStyles.approveButton, { flex: 1, paddingVertical: 10, minHeight: 40 }]
        : [leaveDetailStyles.cancelButton, leaveDetailStyles.approveButton]

    const rejectButtonStyle = showFullWidth 
        ? [leaveDetailStyles.applyButton, leaveDetailStyles.rejectButton, { flex: 1, paddingVertical: 10, minHeight: 40 }]
        : [leaveDetailStyles.applyButton, leaveDetailStyles.rejectButton]

    // 如果是非全宽模式，直接返回按钮而不包装容器
    if (!showFullWidth) {
        return (
            <>
                <TouchableOpacity 
                    style={approveButtonStyle} 
                    onPress={handleApprove}
                >
                    <Icon name="check" type="feather" size={16} color="#fff" />
                    <Text style={[leaveDetailStyles.cancelButtonText, leaveDetailStyles.buttonTextWhite]}>同意</Text>
                </TouchableOpacity>
                
                <TouchableOpacity 
                    style={rejectButtonStyle} 
                    onPress={handleReject}
                >
                    <Icon name="x" type="feather" size={16} color="#fff" />
                    <Text style={[leaveDetailStyles.applyButtonText, leaveDetailStyles.buttonTextWhite]}>不同意</Text>
                </TouchableOpacity>

                {/* 审批意见输入弹窗 */}
                <Modal
                    visible={showApprovalModal}
                    transparent={true}
                    animationType="fade"
                    onRequestClose={handleCloseApprovalModal}
                >
                    <View style={leaveDetailStyles.modalOverlay}>
                        <View style={leaveDetailStyles.modalContent}>
                            <Text style={leaveDetailStyles.modalTitle}>
                                {approvalType === 'approve' ? '审批意见' : '拒绝原因'}
                            </Text>
                            
                            <TextInput
                                style={leaveDetailStyles.modalInput}
                                placeholder={approvalType === 'approve' ? '请输入审批意见（可选）' : '请输入拒绝原因'}
                                value={approvalReason}
                                onChangeText={setApprovalReason}
                                multiline={true}
                                numberOfLines={4}
                                textAlignVertical="top"
                            />
                            
                            <View style={leaveDetailStyles.modalButtons}>
                                <TouchableOpacity 
                                    style={[leaveDetailStyles.modalButton, leaveDetailStyles.modalCancelButton]} 
                                    onPress={handleCloseApprovalModal}
                                >
                                    <Text style={leaveDetailStyles.modalCancelButtonText}>取消</Text>
                                </TouchableOpacity>
                                
                                <TouchableOpacity 
                                    style={[
                                        leaveDetailStyles.modalButton, 
                                        approvalType === 'approve' 
                                            ? leaveDetailStyles.modalApproveButton 
                                            : leaveDetailStyles.modalRejectButton
                                    ]} 
                                    onPress={handleSubmitApproval}
                                >
                                    <Text style={leaveDetailStyles.modalButtonText}>
                                        {approvalType === 'approve' ? '同意' : '拒绝'}
                                    </Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                </Modal>
            </>
        )
    }

    // 全宽模式
    return (
        <View style={buttonContainerStyle}>
            <TouchableOpacity 
                style={approveButtonStyle} 
                onPress={handleApprove}
            >
                <Icon name="check" type="feather" size={16} color="#fff" />
                <Text style={[leaveDetailStyles.cancelButtonText, leaveDetailStyles.buttonTextWhite]}>同意</Text>
            </TouchableOpacity>
            
            <TouchableOpacity 
                style={rejectButtonStyle} 
                onPress={handleReject}
            >
                <Icon name="x" type="feather" size={16} color="#fff" />
                <Text style={[leaveDetailStyles.applyButtonText, leaveDetailStyles.buttonTextWhite]}>不同意</Text>
            </TouchableOpacity>

            {/* 审批意见输入弹窗 */}
            <Modal
                visible={showApprovalModal}
                transparent={true}
                animationType="fade"
                onRequestClose={handleCloseApprovalModal}
            >
                <View style={leaveDetailStyles.modalOverlay}>
                    <View style={leaveDetailStyles.modalContent}>
                        <Text style={leaveDetailStyles.modalTitle}>
                            {approvalType === 'approve' ? '审批意见' : '拒绝原因'}
                        </Text>
                        
                        <TextInput
                            style={leaveDetailStyles.modalInput}
                            placeholder={approvalType === 'approve' ? '请输入审批意见（可选）' : '请输入拒绝原因'}
                            value={approvalReason}
                            onChangeText={setApprovalReason}
                            multiline={true}
                            numberOfLines={4}
                            textAlignVertical="top"
                        />
                        
                        <View style={leaveDetailStyles.modalButtons}>
                            <TouchableOpacity 
                                style={[leaveDetailStyles.modalButton, leaveDetailStyles.modalCancelButton]} 
                                onPress={handleCloseApprovalModal}
                            >
                                <Text style={leaveDetailStyles.modalCancelButtonText}>取消</Text>
                            </TouchableOpacity>
                            
                            <TouchableOpacity 
                                style={[
                                    leaveDetailStyles.modalButton, 
                                    approvalType === 'approve' 
                                        ? leaveDetailStyles.modalApproveButton 
                                        : leaveDetailStyles.modalRejectButton
                                ]} 
                                onPress={handleSubmitApproval}
                            >
                                <Text style={leaveDetailStyles.modalButtonText}>
                                    {approvalType === 'approve' ? '同意' : '拒绝'}
                                </Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </Modal>
        </View>
    )
}

export default ApprovalButtons
